<template>
    <div class="login">
        <div v-show="isShow"></div>
            <div class="top">
                <van-icon name="arrow-left" size="20px" @click="goback()" />
                <div>随手拍</div>
                <img src="../assets/img/erweima.png" @click="goa()" alt="">
            </div>
            <div class="body">
                <img class="img" :src="headerImage" alt="">
                <div class="imgBox">
                    <img class="img1" @click="" src="../assets/img/camre1.png" alt="">
                    <input type="file" id="upload" url="url1" accept="image/*" @change="upload">
                </div>
            </div>
    </div>
</template>

<script>
    import { mapMutations, mapState } from 'vuex'
    import { Toast } from "vant"
    import Exif from 'exif-js'
    export default {
        data() {
            return {
                isShow:false,
                headerImage:require("../assets/img/v2_q0bzdu.png")
            }
        },
        computed: mapState(['userPhone']),
        methods: {
            // 如果methods里面还有其他函数，就要在辅助函数名称的前面加上扩展运算符
            ...mapMutations(['changeToken', 'changeUserid', 'changeuserPhone']),
            // ...mapState(['token', 'userPhone', 'userid']),

            goa() {
                this.$router.push('a')
            },
            goback() {
                this.$router.back()
            },
            upload(e) {
                // files为传进来的图片文件
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length) return;
                this.picValue = files[0];
                // console.log("picValue", this.picValue)
                var timestamp = Date.parse(new Date())
                this.filename = timestamp + this.picValue.name
                this.imgPreview(this.picValue);
            },
            imgPreview(file) {
                let self = this;
                let Orientation;
                //去获取拍照时的信息，解决拍出来的照片旋转问题
                Exif.getData(file, function () {
                    Orientation = Exif.getTag(this, 'Orientation');
                });
                // 看支持不支持FileReader
                if (!file || !window.FileReader) return;

                if (/^image/.test(file.type)) {
                    // 创建一个reader
                    let reader = new FileReader();
                    // 将图片2将转成 base64 格式
                    reader.readAsDataURL(file);
                    // 读取成功后的回调
                    reader.onloadend = function () {
                        let result = this.result;
                        let img = new Image();
                        self.base64 = result
                        img.src = result;
                        // console.log( "img",img.src)
                        //判断图片是否小于100K,是就直接上传，反之压缩图片
                        if (this.result.length <= (300 * 1024)) {
                            self.headerImage = this.result;
                            // console.log("base64", self.headerImage)
                            self.file = self.dataURLtoFile(self.headerImage, self.filename)

                            self.postImg();
                        } else {
                            img.onload = function () {
                                let data = self.compress(img, Orientation);
                                self.headerImage = data;
                                // console.log("base64", self.headerImage)
                                self.file = self.dataURLtoFile(data, self.filename)

                                // console.log(data)
                                self.postImg();
                            }
                        }
                    }
                }
            },
            postImg() {
                //这里写接口
                // console.log("000")
            },
            rotateImg(img, direction, canvas) {
                //最小与最大旋转方向，图片旋转4次后回到原方向    
                const min_step = 0;
                const max_step = 3;
                if (img == null) return;
                //img的高度和宽度不能在img元素隐藏后获取，否则会出错    
                let height = img.height;
                let width = img.width;
                let step = 2;
                if (step == null) {
                    step = min_step;
                }
                if (direction == 'right') {
                    step++;
                    //旋转到原位置，即超过最大值    
                    step > max_step && (step = min_step);
                } else {
                    step--;
                    step < min_step && (step = max_step);
                }
                //旋转角度以弧度值为参数    
                let degree = step * 90 * Math.PI / 180;
                let ctx = canvas.getContext('2d');
                switch (step) {
                    case 0:
                        canvas.width = width;
                        canvas.height = height;
                        ctx.drawImage(img, 0, 0);
                        break;
                    case 1:
                        canvas.width = height;
                        canvas.height = width;
                        ctx.rotate(degree);
                        ctx.drawImage(img, 0, -height);
                        break;
                    case 2:
                        canvas.width = width;
                        canvas.height = height;
                        ctx.rotate(degree);
                        ctx.drawImage(img, -width, -height);
                        break;
                    case 3:
                        canvas.width = height;
                        canvas.height = width;
                        ctx.rotate(degree);
                        ctx.drawImage(img, -width, 0);
                        break;
                }
            },
            compress(img, Orientation) {
                let canvas = document.createElement("canvas");
                let ctx = canvas.getContext('2d');
                //瓦片canvas
                let tCanvas = document.createElement("canvas");
                let tctx = tCanvas.getContext("2d");
                let initSize = img.src.length;
                let width = img.width;
                let height = img.height;
                //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
                let ratio;
                if ((ratio = width * height / 4000000) > 1) {
                    console.log("大于400万像素")
                    ratio = Math.sqrt(ratio);
                    width /= ratio;
                    height /= ratio;
                } else {
                    ratio = 1;
                }
                canvas.width = width;
                canvas.height = height;
                //        铺底色
                ctx.fillStyle = "#fff";
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                //如果图片像素大于100万则使用瓦片绘制
                let count;
                if ((count = width * height / 1000000) > 1) {
                    console.log("超过100W像素");
                    count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
                    //            计算每块瓦片的宽和高
                    let nw = ~~(width / count);
                    let nh = ~~(height / count);
                    tCanvas.width = nw;
                    tCanvas.height = nh;
                    for (let i = 0; i < count; i++) {
                        for (let j = 0; j < count; j++) {
                            tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                        }
                    }
                } else {
                    ctx.drawImage(img, 0, 0, width, height);
                }
                //修复ios上传图片的时候 被旋转的问题
                if (Orientation != "" && Orientation != 1) {
                    switch (Orientation) {
                        case 6://需要顺时针（向左）90度旋转
                            this.rotateImg(img, 'left', canvas);
                            break;
                        case 8://需要逆时针（向右）90度旋转
                            this.rotateImg(img, 'right', canvas);
                            break;
                        case 3://需要180度旋转
                            this.rotateImg(img, 'right', canvas);//转两次
                            this.rotateImg(img, 'right', canvas);
                            break;
                    }
                }
                //进行最小压缩
                let ndata = canvas.toDataURL('image/jpeg', 0.1);
                // console.log('压缩前：' + initSize);
                // console.log('压缩后：' + ndata.length);
                // console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
                tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
                console.log(ndata)

                return ndata;

            },
            dataURLtoFile(dataurl, filename) {//将base64转换为文件
                var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, { type: mime });
            }
        }
    }
</script>

<style lang="scss" scoped>
    .login {
        /* padding-top: 40px; */
    }

    img {
        vertical-align: top;
    }

    .top {
        position: fixed;
        color: white;
        top: 0;
        height: 40px;
        line-height: 40px;
        /* position: relative; */
        font-size: 16px;
        border-bottom: 1px solid #999;
        width: 100%;
        background-color: #4b77e4;
        z-index: 9999;
    }

    .top div {
        text-align: center;

    }

    .van-icon-arrow-left {
        position: absolute;
        top: 10px;
    }

    .top img {
        position: absolute;
        top: 10px;
        width: 20px;
        height: 20px;
        right: 10px;
    }

    .img {
        height: 100%;
        width: 100%;
        margin: -5px 0;
    }

    .body {
        height: calc(100vh - 40px);
        /* height: 100vh; */
        padding-top: 40px;
        position: relative;

    }

    .imgBox {
        position: absolute;
        left: 50%;
        transform: translate(-50%);
        bottom: 40px;
        width: 60px;
        height: 60px;
    }

    .body .img1 {



        width: 40px;
        height: 40px;
        padding: 10px;
        border-radius: 50%;
        background-color: white;

    }

    #upload {
        width: 60px;
        height: 60px;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        opacity: 0;
    }
</style>